<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="材料名称">
              <a-input placeholder="请输入材料名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="材料型号">
              <a-input placeholder="请输入材料型号" v-model="queryParam.modelNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        size="small"
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowKey="(record) => { return record.id }"
        :customRow="setRow"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onSelectAll:onSelectAll,
          onSelect:onSelect,
          onChange: onSelectChange,
          type:'checkbox'
        }"
        @change="handleTableChange">
      </a-table>
    </div>
  </a-modal>
</template>

<script>
  import { filterObj } from '@/utils/util'
  import { getAction } from '@/api/manage'
  import $ from 'jquery'
  export default {
    name: "selectMaterialModal",
    data() {
      return {
        currentSupplierId: 0,
        currentDepositoryId: 0,
        depositoryId: '',
        model: {},
        width: '80%',
        title: "",
        visible: false,
        placement: 'right',
        description: '',
        // 查询条件
        queryParam: {},
        //职务条件
        post: '',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '材料名称',
            align: "center",
            dataIndex: 'materialName'
          },
          {
            title: '型号',
            align: "center",
            dataIndex: 'modelNumber'
          },
          {
            title: '规格',
            align: "center",
            dataIndex: 'specifications'
          },
          {
            title: '品牌',
            align: "center",
            dataIndex: 'brand'
          },
          {
            title: '单位',
            align: "center",
            dataIndex: 'unit'
          },
          {
            title: '市场价',
            align: "center",
            dataIndex: 'marketPrice'
          },
          {
            title: '预算价',
            align: "center",
            dataIndex: 'estimatedCost'
          },
          {
            title: '成本价',
            align: "center",
            dataIndex: 'costPrice'
          }
        ],
        //数据集
        dataSource: [],
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc',
        },
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        url: {
          list: "/ghSupplychainMaterial/listBySupplierId"
        },
        value:0
      }
    },
    created() {

    },
    methods: {
      changeCostTypeValue(value) {
        //this.loadData()
      },
      searchQuery() {
        this.loadData(1);
      },
      searchReset() {
        this.queryParam = {};
        this.loadData(1);
      },
      handleCancel() {
        this.close();
      },
      handleOk() {
        if (this.selectedRows.length == 0){
          this.$message.warning("请至少选择一条记录")
        } else {
          this.$emit('ok', this.selectedRows);
          this.close();
        }
      },
      add(supplierId) {
        this.visible = true;
        this.currentSupplierId = supplierId;
        this.loadData(1);
      },
      //通过仓库id查询材料
      addByDepositoryId(depositoryId){
        this.visible = true;
        this.currentDepositoryId = depositoryId;
        this.loadData(1);
      },
      loadData(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let params = this.getQueryParams();//查询条件
        if (this.currentSupplierId != null && this.currentSupplierId != 0){
          params.supplierId = this.currentSupplierId;
        }
        // if (this.currentDepositoryId != null && this.currentDepositoryId != 0){
        //   params.depositoryId = this.currentDepositoryId;
        // }
        params.depositoryId = this.depositoryId;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records;
            for (let i=0;i<this.dataSource.length;i++){
              this.dataSource[i].key = i;
            }
            if (res.result.total){
              this.ipagination.total = res.result.total;
            }else {
              this.ipagination.total = 0;
            }
          }
        })
      },
      getQueryParams() {
        var param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        param.post = this.post;
        return filterObj(param);
      },
      getQueryField() {
        //TODO 字段权限控制
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if(selected) {
          this.selectedRows.push(record);
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex,1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectedRows = [];
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.loadData();
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.onClearSelected();
        this.queryParam = {};
        $(".clearValue").value = "";
      },
      submitCallback() {
        this.$emit('ok');
        this.visible = false;
      },
      //表格行点击事件
      setRow (record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = [];
              keys = this.selectedRowKeys;
              if(keys.indexOf(record.id) >= 0) {
                flag=true
              }
              if(flag){
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id),1)
              } else {
                keys.push(record.id)
                this.selectedRows.push(record);
              }
            }
          }
        }
      },
    }
  }
</script>

<style scoped lang="less">

  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }
</style>